package com.ibm.android;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;

import com.ibm.android.camera.CameraManager;
import com.ibm.android.decode.DecodeThread;
import com.ibm.android.format.BusinessData;
import com.ibm.android.format.BusinessDataValidator;

public class ScanResultHandler extends Handler {
	DecodeThread mDecodeThread;
	ScanActivity mActivity;

	public ScanResultHandler(ScanActivity scanActivity) {
		int previewFormat = CameraManager.get().getPreviewFormat();
		mDecodeThread = new DecodeThread(this, previewFormat);
		mDecodeThread.start();

		mActivity = scanActivity;

		CameraManager.get().requestPreview(mDecodeThread.getHandler(),
				R.id.decode);
	}

	@Override
	public void handleMessage(Message message) {
		switch (message.what) {
		case R.id.decode_succeeded:
			BusinessDataValidator bdv = new BusinessDataValidator(
					message.obj.toString());
			if (bdv.validate()) {
				final BusinessData bd = new BusinessData(message.obj.toString());
				if (mActivity.history().contains(bd)) {
					CameraManager.get().closeDriver();
					AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
							.create();
					alertDialog.setTitle("Warning:");
					alertDialog
							.setMessage("You already bought this product. \n\nDo you want to buy it again?");
					alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									mActivity.setValidData(bd);
								}
							});
					alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									mActivity.initMain();
								}
							});
					alertDialog.show();

					CameraManager.get().requestPreview(
							mDecodeThread.getHandler(), R.id.decode);
				} else {
					CameraManager.get().closeDriver();
					mActivity.setValidData(bd);
				}
			} else {
				AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
						.create();
				alertDialog.setTitle("Scan result:");
				alertDialog
						.setMessage("Found a QR-Code with unsupported content.\n\nPlease scan a different QR-Code.");
				alertDialog.setButton("Ok",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								CameraManager.get()
										.requestPreview(
												mDecodeThread.getHandler(),
												R.id.decode);
							}
						});
				alertDialog.show();
			}
			break;
		case R.id.decode_failed:
			CameraManager.get().requestPreview(mDecodeThread.getHandler(),
					R.id.decode);
			break;
		}
	}
}
